<template>
  <div class="admin-dishes-container">
    <el-card class="header-card">
      <div class="header-content">
        <h2><el-icon><ShoppingBag /></el-icon> 菜品管理</h2>
        <el-button type="primary" :icon="Plus" @click="showAddDialog">添加菜品</el-button>
        </div>
    </el-card>

    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchForm.dishName"
            placeholder="菜品名称"
            clearable
            @clear="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="searchForm.dishType"
            placeholder="菜品类型"
            clearable
            @clear="handleSearch"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card v-loading="loading">
      <el-table :data="dishes" stripe style="width: 100%; height: 600px;">
        <el-table-column prop="dishId" label="ID" width="80" />
        <el-table-column label="图片" width="100">
          <template #default="{ row }">
            <el-image
              :src="getImageUrl(row.dishImage || '')"
              fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px;"
            />
          </template>
        </el-table-column>
        <el-table-column prop="dishName" label="菜品名称" min-width="150" />
        <el-table-column prop="dishType" label="类型" width="120" />
        <el-table-column prop="dishPrice" label="单价" width="100">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold;">¥{{ row.dishPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="salesCount" label="销量" width="100" />
        <el-table-column prop="dishStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.dishStatus === '0' ? 'success' : 'danger'">
              {{ row.dishStatus === '0' ? '正常' : '停售' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="showEditDialog(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" :icon="Comment" @click="showCommentsDialog(row)">
              查看评论
            </el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row.dishId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showDishDialog"
      :title="isEditMode ? '编辑菜品' : '添加菜品'"
      width="600px"
      @close="resetDishForm"
    >
      <el-form :model="dishForm" :rules="dishRules" ref="dishFormRef" label-width="100px">
        <el-form-item label="菜品名称" prop="dishName">
          <el-input v-model="dishForm.dishName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品类型" prop="dishType">
          <el-input v-model="dishForm.dishType" placeholder="请输入菜品类型" />
        </el-form-item>
        <el-form-item label="菜品单价" prop="dishPrice">
          <el-input-number v-model="dishForm.dishPrice" :min="0" :precision="2" :step="1" />
        </el-form-item>
        <el-form-item label="菜品图片" prop="dishImage">
          <div class="image-upload-container">
            <el-upload
              class="image-uploader"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
              :http-request="handleImageUpload"
              accept="image/*"
            >
              <el-image
                v-if="dishForm.dishImage"
                :src="getImageUrl(dishForm.dishImage)"
                class="uploaded-image"
                fit="cover"
                @error="handleImageError"
              />
              <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="image-actions" v-if="dishForm.dishImage">
              <el-button size="small" @click="dishForm.dishImage = ''">删除图片</el-button>
            </div>
          </div>
          <el-input
            v-model="dishForm.dishImage"
            placeholder="或直接输入图片URL"
            style="margin-top: 10px; width: 100%;"
            :maxlength="1000"
            show-word-limit
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="菜品描述">
          <el-input v-model="dishForm.dishDescription" type="textarea" :rows="3" placeholder="请输入菜品描述" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="菜品规格">
          <el-input v-model="dishForm.dishSpecification" placeholder="小中大份" />
        </el-form-item>
        <el-form-item label="菜品材料">
          <el-input v-model="dishForm.dishMaterials" type="textarea" :rows="2" placeholder="请输入菜品材料" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="菜品状态" prop="dishStatus">
          <el-radio-group v-model="dishForm.dishStatus">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停售</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDishDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitDish" :loading="submitting">
          {{ isEditMode ? '保存' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 评论管理对话框 -->
    <el-dialog
      v-model="showCommentsListDialog"
      title="评论管理"
      width="800px"
    >
      <el-table :data="dishComments" stripe style="width: 100%">
        <el-table-column prop="commentId" label="ID" width="80" />
        <el-table-column label="用户" width="120">
          <template #default="{ row }">
            {{ row.user?.nickname || '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="评分" width="120">
          <template #default="{ row }">
            <el-rate v-model="row.rating" disabled size="small" />
          </template>
        </el-table-column>
        <el-table-column prop="commentContent" label="评论内容" min-width="200" />
        <el-table-column prop="commentStatus" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.commentStatus === '0' ? 'success' : 'info'">
              {{ row.commentStatus === '0' ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="handleDeleteComment(row.commentId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Plus, Search, Edit, Delete, Comment, ShoppingBag } from '@element-plus/icons-vue';
import { getAllDishes, getDishesByName, createDish, updateDish, deleteDish } from '@/api/dish';
import { getDishesByType } from '@/api/dish';
import { getCommentsByDishId, deleteComment } from '@/api/comment';
import { getUserById } from '@/api/user';
import { uploadFile } from '@/api/file';
import type { Dish, Comment as CommentType } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

const loading = ref(false);
const submitting = ref(false);
const showDishDialog = ref(false);
const showCommentsListDialog = ref(false);
const isEditMode = ref(false);
const dishFormRef = ref<FormInstance>();

const dishes = ref<Dish[]>([]);
const dishComments = ref<CommentType[]>([]);
const currentDish = ref<Dish | null>(null);

const searchForm = reactive({
  dishName: '',
  dishType: ''
});

const dishForm = reactive({
  dishId: undefined as number | undefined,
  dishName: '',
  dishType: '',
  dishPrice: 0,
  dishImage: '',
  dishDescription: '',
  dishSpecification: '',
  dishMaterials: '',
  dishStatus: '0' as '0' | '1'
});

const dishRules: FormRules = {
  dishName: [{ required: true, message: '请输入菜品名称', trigger: 'blur' }],
  dishType: [{ required: true, message: '请输入菜品类型', trigger: 'blur' }],
  dishPrice: [{ required: true, message: '请输入菜品单价', trigger: 'blur' }]
};

// 加载菜品列表
const loadDishes = async () => {
  loading.value = true;
  try {
    const response = await getAllDishes();
    if (response.operateResult === 'SUCC' && response.data) {
      dishes.value = response.data;
    } else {
      dishes.value = [];
    }
  } catch (error) {
    ElMessage.error('加载菜品失败');
    dishes.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索菜品
const handleSearch = async () => {
  if (!searchForm.dishName && !searchForm.dishType) {
    await loadDishes();
    return;
  }
  
  loading.value = true;
  try {
    let response;
    // 情况1：同时按名称和类型
    if (searchForm.dishName && searchForm.dishType) {
      response = await getDishesByName(searchForm.dishName);
      if (response.operateResult === 'SUCC' && response.data) {
        dishes.value = response.data.filter(d => (d.dishType || '').includes(searchForm.dishType));
      } else {
        dishes.value = [];
      }
      return;
    }

    // 情况2：只按名称
    if (searchForm.dishName) {
      response = await getDishesByName(searchForm.dishName);
    }

    // 情况3：只按类型
    if (!searchForm.dishName && searchForm.dishType) {
      response = await getDishesByType(searchForm.dishType);
    }
     
    if (response && response.operateResult === 'SUCC' && response.data) {
      dishes.value = response.data;
    } else {
      dishes.value = [];
    }
  } catch (error) {
    ElMessage.error('搜索失败');
  } finally {
    loading.value = false;
  }
};

// 显示添加对话框
const showAddDialog = () => {
  isEditMode.value = false;
  showDishDialog.value = true;
};

// 显示编辑对话框
const showEditDialog = (dish: Dish) => {
  isEditMode.value = true;
  dishForm.dishId = dish.dishId;
  dishForm.dishName = dish.dishName;
  dishForm.dishType = dish.dishType;
  dishForm.dishPrice = dish.dishPrice;
  dishForm.dishImage = dish.dishImage || '';
  dishForm.dishDescription = dish.dishDescription || '';
  dishForm.dishSpecification = dish.dishSpecification || '';
  dishForm.dishMaterials = dish.dishMaterials || '';
  dishForm.dishStatus = dish.dishStatus || '0';
  showDishDialog.value = true;
};

// 提交菜品
const handleSubmitDish = async () => {
  if (!dishFormRef.value) return;
  
  await dishFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
      submitting.value = true;
      try {
        let response;
      if (isEditMode.value && dishForm.dishId) {
        response = await updateDish(dishForm.dishId, { ...dishForm });
        } else {
        response = await createDish({ ...dishForm });
        }

        if (response.operateResult === 'SUCC') {
        ElMessage.success(isEditMode.value ? '更新成功' : '添加成功');
        showDishDialog.value = false;
        await loadDishes();
        } else {
          ElMessage.error(response.errorMsg || '操作失败');
        }
      } catch (error: any) {
        ElMessage.error(error.message || '操作失败');
      } finally {
        submitting.value = false;
    }
  });
};

// 删除菜品
const handleDelete = (dishId: number) => {
  ElMessageBox.confirm('确定要删除该菜品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteDish(dishId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        await loadDishes();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};

// 显示评论对话框
const showCommentsDialog = async (dish: Dish) => {
  currentDish.value = dish;
  try {
    const response = await getCommentsByDishId(dish.dishId!);
    if (response.operateResult === 'SUCC' && response.data) {
      // 加载每个评论的用户信息
      const commentsWithUsers = await Promise.all(
        response.data.map(async (comment) => {
          const userRes = await getUserById(comment.userId);
          if (userRes.operateResult === 'SUCC' && userRes.data) {
            return { ...comment, user: userRes.data };
          }
          return comment;
        })
      );
      dishComments.value = commentsWithUsers;
    } else {
      dishComments.value = [];
    }
    showCommentsListDialog.value = true;
  } catch (error) {
    ElMessage.error('加载评论失败');
  }
};

// 删除评论
const handleDeleteComment = (commentId: number) => {
  ElMessageBox.confirm('确定要删除该评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteComment(commentId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('删除成功');
        if (currentDish.value) {
          await showCommentsDialog(currentDish.value);
        }
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};

// 重置表单
const resetDishForm = () => {
  dishFormRef.value?.resetFields();
  dishForm.dishId = undefined;
  dishForm.dishName = '';
  dishForm.dishType = '';
  dishForm.dishPrice = 0;
  dishForm.dishImage = '';
  dishForm.dishDescription = '';
  dishForm.dishSpecification = '';
  dishForm.dishMaterials = '';
  dishForm.dishStatus = '0';
};

// 图片上传前验证
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!');
    return false;
  }
  return true;
};

// 处理图片上传
const handleImageUpload = async (options: any) => {
  const { file } = options;
  try {
    const response = await uploadFile(file);
    if (response.operateResult === 'SUCC' && response.data) {
      dishForm.dishImage = response.data;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error(response.errorMsg || '图片上传失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '图片上传失败');
  }
};

// 获取图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath) return '';
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  return `http://localhost:8060${imagePath}`;
};

// 处理图片加载错误
const handleImageError = (error: any) => {
  ElMessage.error('图片加载失败，请检查图片路径或重新上传');
};

onMounted(() => {
  loadDishes();
});
</script>

<style scoped>
.admin-dishes-container {
  animation: fadeIn 0.5s ease-out;
  position: relative;
  z-index: 1;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 美化卡片样式 */
:deep(.el-card) {
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: none;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.9);
}

/* 美化按钮样式 */
:deep(.el-button) {
  border-radius: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.4);
}

/* 美化输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 美化表格样式 */
:deep(.el-table) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
}

:deep(.el-table th) {
  background: transparent;
  color: #4a5568;
  font-weight: 600;
  border-bottom: 2px solid #e2e8f0;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f1f5f9;
}

:deep(.el-table tr:hover > td) {
  background-color: rgba(102, 126, 234, 0.05);
}

/* 美化模态框样式 */
:deep(.el-dialog) {
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
  border: none;
  backdrop-filter: blur(20px);
  background: rgba(255, 255, 255, 0.95);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 20px 20px 0 0;
  padding: 20px 24px;
  margin: 0;
}

:deep(.el-dialog__title) {
  font-weight: 700;
  font-size: 18px;
}

:deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 24px;
  color: white;
}

:deep(.el-dialog__body) {
  padding: 32px 24px;
  background: rgba(255, 255, 255, 0.8);
}

/* 美化图片上传区域 */
.image-upload-container {
  border-radius: 12px;
  overflow: hidden;
}

.image-uploader {
  border: 2px dashed #cbd5e0;
  border-radius: 12px;
  width: 100%;
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  transition: all 0.3s ease;
  cursor: pointer;
}

.image-uploader:hover {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
}

.image-uploader-icon {
  font-size: 48px;
  color: #a0aec0;
  transition: all 0.3s ease;
}

.image-uploader:hover .image-uploader-icon {
  color: #667eea;
  transform: scale(1.1);
}

.image-actions {
  margin-top: 12px;
  text-align: center;
}

/* 美化标签样式 */
:deep(.el-tag) {
  border-radius: 8px;
  font-weight: 600;
  border: none;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  color: white;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  color: white;
}

/* 美化分页样式 */
:deep(.el-pagination) {
  justify-content: center;
  margin-top: 24px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 8px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .el-pager li:hover) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

:deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 美化搜索区域 */
.search-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 250, 252, 0.9) 100%);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 美化操作按钮 */
:deep(.el-button--success) {
  background: linear-gradient(135deg, #48bb78 0%, #38a169 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(72, 187, 120, 0.3);
}

:deep(.el-button--success:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(72, 187, 120, 0.4);
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #ed8936 0%, #dd6b20 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(237, 137, 54, 0.3);
}

:deep(.el-button--warning:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(237, 137, 54, 0.4);
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #f56565 0%, #e53e3e 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(245, 101, 101, 0.3);
}

:deep(.el-button--danger:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(245, 101, 101, 0.4);
}

/* 美化图片显示 */
:deep(.el-image) {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.el-image:hover) {
  transform: scale(1.05);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

/* 美化加载状态 */
:deep(.el-loading-mask) {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

:deep(.el-loading-spinner) {
  color: #667eea;
}

/* 美化消息提示 */
:deep(.el-message) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

:deep(.el-message--success) {
  background: linear-gradient(135deg, rgba(72, 187, 120, 0.9) 0%, rgba(56, 161, 105, 0.9) 100%);
  border: none;
}

:deep(.el-message--error) {
  background: linear-gradient(135deg, rgba(245, 101, 101, 0.9) 0%, rgba(229, 62, 62, 0.9) 100%);
  border: none;
}

:deep(.el-message--warning) {
  background: linear-gradient(135deg, rgba(237, 137, 54, 0.9) 0%, rgba(221, 107, 32, 0.9) 100%);
  border: none;
}

.header-card {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #303133;
}

.search-card {
  margin-bottom: 20px;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  display: block;
}

.uploaded-image {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 6px;
}

.image-actions {
  margin-top: 10px;
}
</style>
